<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input 
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          v-model="queryParams.keyword"
          @input="changeValue"
          placeholder="输入员工姓名全员搜索" />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true" v-permission="'import'">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee" v-permission="'abc'">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <el-table-column prop="formOfEmployment" label="聘用形式">
                <template v-slot="{ row }">
                  <span v-if="row.formOfEmployment === 1">正式</span>
                  <span v-else-if="row.formOfEmployment === 2">非正式</span>
                  <span v-else>无</span>
                </template>
            </el-table-column>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template v-slot="{row}">
              <el-button
                @click="$router.push(`/employee/detail/${row.id}`)"
                size="mini"
                type="text">查看</el-button>
              
              <el-button size="mini" type="text" @click="hAssignRole(row)">角色</el-button>
              <el-popconfirm title="确认删除该行数据吗？"  @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>

    <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="loadEmployeeList"/>
    
    <AssignRole ref="assignRole" :curEmployeId="curEmployeId" :showRoleDialog.sync="showRoleDialog"/>
  </div>
</template>

<script>
import ImportExcel from './components/import-excel.vue'
import AssignRole from './components/assignRole.vue'
import { getEmployeeList, delEmployee } from '@/api/employee'
import { getDepartment } from '@/api/department'
import { arr2tree } from '@/utils'
import FileSaver from 'file-saver'
import { exportEmployee } from '@/api/employee'

const throttle = (fn, t=300) => {
  // debugger;
  console.log('throttle', this)
  let timer = null
  return function(...arg) {
    console.log('function', this)
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this)
    }, t)
  }
}
export default {
  name: 'Employee',
  components: {
    ImportExcel,
    AssignRole
  },
  data() {
    return {
      list: [],
      depts: [], // 组织数据
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1, // 当前页码
        pagesize: 3
      },
      total: 0, // 记录员工的总数
      keyword: '', // 模糊搜索字段
      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      showRoleDialog: false, // 用来控制角色弹层的显示
      curEmployeId: ''
    }
  },
  created() {
    this.loadDepartment()
  },
  methods: {
    hAssignRole({id}) {
      console.log('当前要分配角色id是', id)
      this.curEmployeId = id
      this.showRoleDialog = true

      this.$nextTick(() => {
        this.$refs.assignRole.getUserRole()
      })
    },
    // changeValue() {
    //   // 单位时间内只执行最后一次
    //   // this的实例上赋值了一个timer的属性
    //   clearTimeout(this.timer) // 清理上一次的定时器
    //   this.timer = setTimeout(() => {
    //     this.queryParams.page = 1
    //     this.loadEmployeeList()
    //   }, 300)
    // },
    fn(){
      this.queryParams.page = 1
      this.loadEmployeeList()
    },
    // changeValue: throttle(function(){ this.fn() }),
    changeValue: throttle(function(){
      this.fn()}),
    selectNode(node) {
      console.log(node)
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1 // 设置第一页
      // 这个时候参数 记录了id
      this.loadEmployeeList()
    },
    async loadDepartment() {
      // 递归方法 将列表转化成树形
      // let result = await getDepartment()
      this.depts = arr2tree(await getDepartment(), 0)
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.depts[0].id)
      })
      // 这个时候参数 记录了id
      this.loadEmployeeList()
    },
    // 获取员工列表的方法
    async loadEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    // 切换页码
    changePage(newPage) {
      this.queryParams.page = newPage // 赋值新页码
      this.loadEmployeeList() // 查询数据
    },
    async  exportEmployee() {
      const result = await exportEmployee() // 导出所有的员工接口
      // console.log(result) // 使用一个npm包 直接将blob文件下载到本地 file-saver
      // FileSaver.saveAs(blob对象,文件名称)
      FileSaver.saveAs(result, '员工信息表.xlsx') // 下载文件
    },
    // 删除员工方法
    async confirmDel(id) {
      await delEmployee(id)
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.loadEmployeeList()
      this.$message.success('删除员工成功')
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>